package com.yuandian.management.utils;


import lombok.extern.slf4j.Slf4j;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * <p>
 * AES加密工具类
 * </p>
 * <p>是一种可逆加密算法，对用户的敏感信息加密处理 对原始数据进行AES加密后，在进行Base64编码转化；</p>
 *
 * @author: tangqingchun
 * @date: 2021/04/09
 *
*/
@Slf4j
public class AESUtil {
    /**
     * 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式，key需要为16位。
     */
    private static String KEY = "abcdef0123456789";
    /**
     * 向量iv
     */
    private static String IV = "0123456789abcdef";

    private static IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());

    private AESUtil() {
    }

    /**
     * 加密
     *
     * @param content 待加密串
     * @return
     */
    public static String encrypt(String content) {
        String result = "";
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] raw = KEY.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);
            byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
            result = Base64.encode(encrypted);
        } catch (Exception e) {
            log.error("AES加密异常", e);
        }
        // 此处使用BASE64做转码。
        return result;

    }

    /**
     * 解密
     *
     * @param content 待解密串
     * @return
     */
    public static String decrypt(String content) {
        String result = "";
        try {
            byte[] raw = KEY.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
            // 先用base64解密
            byte[] encrypted1 = Base64.decode(content);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, "utf-8");
        } catch (Exception e) {
            log.error("AES解密异常", e);
        }
        return result;
    }

    public static void main(String[] args) {
        // 需要加密的字串
        String cSrc = "400";
        System.out.println(cSrc + "  长度为" + cSrc.length());
        // 加密
        long lStart = System.currentTimeMillis();
        String enString = AESUtil.encrypt(cSrc);
        System.out.println("加密后的字串是：" + enString);

        long lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("加密耗时：" + lUseTime + "毫秒");
        // 解密
        lStart = System.currentTimeMillis();
        String DeString = AESUtil.decrypt(enString);
        System.out.println("解密后的字串是：" + DeString);
        lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("解密耗时：" + lUseTime + "毫秒");
    }
}
